<?php

namespace App\Command\ResumeParsing\Service\ParsingSpecial;

use App\Service\FileHandler;
use EchoPHP\Facades\Log;

class ParsingZhilian2 extends ParsingSpecialXml {

    function __construct($helper) {
        parent::__construct($helper);
        $this->titleXpath = "//body/div/p[b/span[contains(@style, 'background:#D9D9D9')]]";

        $this->get['template'] = function () {
            $this->listXPath("//templateTag[normalize-space()='templateTagName']");    //[contains(., 'templateTagName')][starts-with(normalize-space(), 'templateTagName')]
            $result = $this->xPath->query();
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['id'] = function () {
            //$this->listXPath("//body/div/p[starts-with(normalize-space(), 'ID') and contains(., '：')]");
            $result = $this->xPath->query("//body/div/p[starts-with(normalize-space(), 'ID') and contains(., '：')]");
            if ($result->length < 1) return '';
            return $this->preg_get('/(?:ID\s*：)\s*(?<result>.*?)\s*(?=$)/u', $result[0]->textContent, array('groupName' => 'result'));
        };

        $this->get['time'] = function () {
            //$this->listXPath("//table/tr/td[starts-with(normalize-space(), '简历更新时间：')]/following-sibling::td[1]");
            $result = $this->xPath->query("//table/tr/td[starts-with(normalize-space(), '简历更新时间：')]/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent, TRUE);
        };

        $this->get['name'] = function () {
            //$this->listXPath("//table/tr/td/table/tr/td[p/b/span[contains(@style, 'font-size:16.0pt')] and contains(following-sibling::td, '手机：')][1]");
            $result = $this->xPath->query("//table/tr/td/table/tr/td[p/b/span[contains(@style, 'font-size:16.0pt')]][1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent, TRUE);
        };

        $this->groupGetter['basic'] = array();

        $this->groupGetter['basic'][0] = function () {
            //$this->listXPath("//table/tr[td/table/tr/td[p/b/span[contains(@style, 'font-size:16.0pt')] and contains(following-sibling::td, '手机：')]]/following-sibling::tr[1]/td[1]/p[1]");
            $result = $this->xPath->query("//table/tr[td/table/tr/td[p/b/span[contains(@style, 'font-size:16.0pt')]]]/following-sibling::tr[1]/td[1]/p[1]");
            if ($result->length < 1) return '';
            return preg_split('/\s+/u', trim($result[0]->textContent));
        };

        $this->groupGetter['basic'][] = function ($text) {
            if (preg_match('/^[男女]$/u', $text)) {
                return array('sex' => $text);
            }
        };

        $this->groupGetter['basic'][] = function ($text) {
            if (preg_match('/^\d{2}岁$/u', $text)) {
                return array('age' => $text);
            }
        };

        $this->groupGetter['basic'][] = function ($text) {
            if (preg_match('/(?<=\()(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?|(?:19|20)?\d{2}\s*(?<delimiter>[\-\.\/\\\\])\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?(?=\))/u', $text, $matches)) {
                return array('birthday' => $matches[0]);
            }
        };

        $this->groupGetter['basic'][] = function ($text) {
            $text = $this->formatTxt($text, TRUE);
            if (preg_match('/^(?:\d{1,2}\s*年(?:\s*[01]?\d\s*个?月)?|\d{1,2}\s*个?月)(?:\s*以上|\+)?(?=工作经验)/u', $text, $matches)) {
                return array('workyear' => $matches[0]);
            }
        };

        $this->groupGetter['basic'][] = function ($text) {
            static $dictDegree = array(
                "博士后" => 9,
                "博士" => 9,
                "MBA" => 8,
                "EMBA" => 8,
                "硕士" => 7,
                "本科" => 6,
                "大专" => 5,
                "中专" => 4,
                "中技" => 3,
                "中技" => 3,
                "高中" => 2,
                "中学" => 1,
                "初中" => 1,
                "初中以下" => 1,
                "初中及以下" => 1,
                "小学" => 1
            );
            if (isset($dictDegree[$text])) return array('degree' => $text);
        };

        $this->groupGetter['basic'][] = function ($text) {
            static $dictMarried = array("未婚" => 0, "已婚" => 0, "保密" => 2);
            if (isset($dictMarried[$text])) return array('married' => $text);
        };

        $this->get['sex'] = $this->groupGet('sex', 'basic');

        $this->get['nation'] = $this->tagNotExist;

        $this->get['identitycard'] = $this->tagNotExist;

        $this->get['mobile'] = function () {
            //$this->listXPath("//table/tr/td/p/span[contains(., '手机：') and contains(@style, 'font-size:9.0pt')]");
            $result = $this->xPath->query("//table/tr/td/p/span[contains(., '手机：') and contains(@style, 'font-size:9.0pt')]");
            if ($result->length < 1) return '';
            return $this->preg_get('/(?:手机\s*[:：])\s*(?<result>.*?)\s*(?=\||$|\D)/mu', $this->recoverText($result[0]->textContent), array('groupName' => 'result'));
        };

        $this->get['email'] = function () {
            //$this->listXPath("//table/tr/td/p/span[contains(., 'E-mail：') and contains(@style, 'font-size:9.0pt')]");
            $result = $this->xPath->query("//table/tr/td/p/span[contains(., 'E-mail：') and contains(@style, 'font-size:9.0pt')]");
            if ($result->length < 1) return '';
            return $this->preg_get('/(?:E-mail\s*[:：])\s*(?<result>.*?)\s*(?=\||$)/mu', $this->recoverText($result[0]->textContent), array('groupName' => 'result'));
        };

        $this->get['age'] = $this->groupGet('age', 'basic');

        $this->get['married'] = $this->groupGet('married', 'basic');

        $this->groupGetter['address'] = array();

        $this->groupGetter['address'][0] = function () {
            //$this->listXPath("//table/tr[td/table/tr/td[p/b/span[contains(@style, 'font-size:16.0pt')] and contains(following-sibling::td, '手机：')]]/following-sibling::tr[1]/td[1]/p[2]");
            $result = $this->xPath->query("//table/tr[td/table/tr/td[p/b/span[contains(@style, 'font-size:16.0pt')]]]/following-sibling::tr[1]/td[1]/p[2]");
            if ($result->length < 1) return '';
            return preg_split('/\s*\|\s*/u', trim($result[0]->textContent));
        };

        $this->groupGetter['address'][] = function ($text) {
            if (preg_match('/现居住地\s*：\s*(?<result>.*)$/u', $text, $matches)) {
                return array('workarea' => $matches['result']);
            }
        };

        $this->groupGetter['address'][] = function ($text) {
            if (preg_match('/户口\s*：\s*(?<result>.*)$/u', $text, $matches)) {
                return array('area' => $matches['result']);
            }
        };

        $this->groupGetter['address'][] = function ($text) {
            static $dictMarried = array("中共党员" => '01', "团员" => '02', "民主党派" => '03', "无党派人士" => '04', "群众" => '05', "其他" => '06');
            if (isset($dictMarried[$text])) return array('politic' => $text);
        };

        $this->get['politic'] = $this->groupGet('politic', 'address');

        $this->get['degree'] = $this->groupGet('degree', 'basic');

        $this->get['industry'] = function () {
            //$this->listXPath("//table/tr/td[normalize-space()='期望从事行业：']/following-sibling::td[1]");
            $result = $this->xPath->query("//table/tr/td[normalize-space()='期望从事行业：']/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent, TRUE);
        };

        $this->get['position'] = $this->tagNotExist;

        $this->get['career'] = function () {
            //$this->listXPath("//table/tr/td[normalize-space()='期望从事职业：']/following-sibling::td[1]");
            $result = $this->xPath->query("//table/tr/td[normalize-space()='期望从事职业：']/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent, TRUE);
        };

        $this->get['major'] = $this->tagNotExist;

        $this->get['birthday'] = $this->groupGet('birthday', 'basic');

        $this->get['workyear'] = $this->groupGet('workyear', 'basic');

        $this->get['workarea'] = $this->groupGet('workarea', 'address');

        $this->get['expectarea'] = function () {
            //$this->listXPath("//table/tr/td[normalize-space()='期望工作地区：']/following-sibling::td[1]");
            $result = $this->xPath->query("//table/tr/td[normalize-space()='期望工作地区：']/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent, TRUE);
        };

        $this->get['area'] = $this->groupGet('area', 'address');

        $this->get['salary'] = $this->tagNotExist;

        $this->get['expectsalary'] = function () {
            //$this->listXPath("//table/tr/td[normalize-space()='期望月薪：']/following-sibling::td[1]");
            $result = $this->xPath->query("//table/tr/td[normalize-space()='期望月薪：']/following-sibling::td[1]");
            if ($result->length < 1) return '';
            $resultText = $this->formatTxt($result[0]->textContent, TRUE);
            $expectsalary = $this->func->parseSalary($resultText);
            if (count($expectsalary)) {
                $this->helper->resumeInfo['expectsalaryfrom'] = $expectsalary['monthly']['begin'];
                $this->helper->resumeInfo['expectsalaryend'] = $expectsalary['monthly']['end'];
                //$this->helper->resumeInfo['expectsalaryafrom'] = $expectsalary['annual']['begin'];
                //$this->helper->resumeInfo['expectsalaryaend'] = $expectsalary['annual']['end'];
            }
            return $resultText;
        };

        $this->get['jobterm'] = function () {
            //$this->listXPath("//table/tr/td[normalize-space()='期望工作性质：']/following-sibling::td[1]");
            $result = $this->xPath->query("//table/tr/td[normalize-space()='期望工作性质：']/following-sibling::td[1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent, TRUE);
        };

        $this->get['school'] = $this->tagNotExist;

        $this->get['nofocuse'] = $this->tagNotExist;

        $this->get['workinfo'] = function () {
            $tableArr = $this->getPart('工作经历', TRUE);
            if (!count($tableArr)) return array();
            $data = array();
            foreach ($tableArr as $table) {
                $item = array('comment' => '');
                $time_company = $this->xPath->query("tr[1]", $table);
                if ($time_company->length) {
                    if (preg_match('/^(?<time>(?<!\d)(?:(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?|(?:19|20)?\d{2}\s*(?<delimiter>[\-\.\/\\\\])\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?)(?!\d)(?:(?:\s*[-–—\/\\\\~到至]\s*)(?<!\d)(?:至今|现在|(?(delimiter)(?:19|20)?\d{2}\s*\k<delimiter>\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?|(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?))(?!\d))?)\s*(?<company>.+?)\s*(?:[(（](?<timespan>(?:\d{1,2}年(?:\s{0,2}[01]?\d个?月)?|\d{1,2}个?月)(?:以上|\+)?)[)）])?$/u', $this->formatTxt($time_company[0]->textContent, TRUE), $matches)) {
                        $time = $matches['time'];
                        $tmp = $this->func->parseTimespan($time);
                        $item['comment'] = !empty($matches['timespan']) ? '工作时间：' . $matches['timespan'] : '';
                        $item['time'] = $time;
                        $item['time_from'] = $tmp['begin'];
                        $item['time_end'] = $tmp['end'];
                        $item['company'] = $matches['company'];
                    }
                }
                $duty_salary = $this->xPath->query("tr[2]", $table);
                if ($duty_salary->length && preg_match('/^(?<duty>.*?)??\s*\|?\s*(?<salary>面议|保密|\d+(?:\.\d+)?\s*[kw万]?\s*元?(?:\s*[-–—~～至到]\s*(?:\d+(?:\.\d+)?\s*[kw万]?)\s*元?)?\s*[\/每].*?)??(?:以上|以下)?$/u', $this->formatTxt($duty_salary[0]->textContent, TRUE), $matches)) {
                    $item['duty'] = !empty($matches['duty']) ? $matches['duty'] : '';
                    $item['salary'] = !empty($matches['salary']) ? $matches['salary'] : '';
                }
                $comment = $this->xPath->query("tr[2]/following-sibling::tr", $table);
                foreach ($comment as $i => $tr) {
                    $text = $this->formatTxt($tr->textContent, 'space');
                    if ($i == 0 && strpos($text, '工作描述：') === false) {
                        if (preg_match('/^(?<industry>.+?)(?:\s+\|\s+(?<comment>.+))?$/u', $text, $matches)) {
                            $item['industry'] = $matches['industry'];
                            if (!empty($matches['comment'])) $item['comment'] .= "\r\n" . $matches['comment'];
                        } else {
                            $item['industry'] = $text;
                        }
                    } else {
                        $text = preg_replace('/^工作描述：\s*/u', '', $this->formatTxt($tr->textContent));
                        $item['comment'] .= "\r\n" . $text;
                    }

                }
                $item['comment'] = trim($item['comment']);
                $data[] = $item;
            }
            return $data;
        };

        $this->get['projectinfo'] = function () {
            $result = $this->getPart('项目经历', TRUE);
            if (!count($result)) return '';
            $trArr = $this->xPath->query("tr", $result[0]);
            $data = array();
            foreach ($trArr as $tr) {
                if (count($this->xPath->query("self::tr[contains(@style,'mso-yfti-irow:0;mso-yfti-firstrow:yes')]", $tr)) && preg_match('/^(?<time>(?<!\d)(?:(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?|(?:19|20)?\d{2}\s*(?<delimiter>[\-\.\/\\\\])\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?)(?!\d)(?:(?:\s*[-–—\/\\\\~到至]\s*)(?<!\d)(?:至今|现在|(?(delimiter)(?:19|20)?\d{2}\s*\k<delimiter>\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?|(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?))(?!\d))?)\s*(?<project>.+?)\s*(?:[(（](?<timespan>(?:\d{1,2}年(?:\s{0,2}[01]?\d个?月)?|\d{1,2}个?月)(?:以上|\+)?)[)）])?$/u', $this->formatTxt($tr->textContent, TRUE), $matches)) {
                    if (isset($item)) {
                        $item['comment'] = trim($item['comment']);
                        $data[] = $item;
                    }
                    $time = $matches['time'];
                    $tmp = $this->func->parseTimespan($time);
                    $item = array('comment' => !empty($matches['timespan']) ? '项目时间：' . $matches['timespan'] : '', 'time' => $time, 'time_from' => $tmp['begin'], 'time_end' => $tmp['end'], 'project' => $matches['project']);
                } else {
                    $tdArr = $this->xPath->query("td", $tr);
                    if (isset($item)) {
                        foreach ($tdArr as $td) {
                            $item['comment'] .= "\r\n" . $this->formatTxt($td->textContent);
                        }
                    }
                }
            }
            if (isset($item)) {
                $item['comment'] = trim($item['comment']);
                $data[] = $item;
            }
            return $data;
        };

        $this->get['educationinfo'] = function () {
            $result = $this->getPart('教育经历', TRUE);
            if (!count($result)) return '';
            $trArr = $this->xPath->query("tr", $result[0]);
            $data = [];
            foreach ($trArr as $tr) {
                if (preg_match('/^(?<time>(?:(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?|(?:19|20)?\d{2}\s*(?<delimiter>[\-\.\/\\\\])\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?)(?!\d)(?:(?:\s*[-–—\/\\\\~～到至]\s*)(?<!\d)(?:至今|现在|(?(delimiter)(?:19|20)?\d{2}\s*\k<delimiter>\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?|(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?))))\s+(?<school>.+?)\s+(?<major>.+?)\s+(?<degree>.+?)$/u', trim($tr->textContent), $matches)) {
                    $time = $matches['time'];
                    $tmp = $this->func->parseTimespan($time);
                    $data[] = array('comment' => '', 'time' => $time, 'time_from' => $tmp['begin'], 'time_end' => $tmp['end'], 'school' => $matches['school'], 'major' => $matches['major'], 'degree' => $matches['degree'],);
                }
            }
            return $data;
        };

        $this->get['skillinfo'] = function () {
            $resultText = $this->getPart('专业技能');
            foreach (['语言能力', '特殊技能'] as $title) {
                if ($part = $this->getPart($title)) $resultText .= "\r\n\r\n" . $title . "\r\n" . preg_replace('/\s*：\s+/u', '：', $part);
            }
            return trim($resultText);
        };

        $this->get['awardinfo'] = $this->tagNotExist;

        $this->get['commentinfo'] = function () {
            return $this->getPart('自我评价');
        };

        $this->get['otherinfo'] = function () {
            $resultText = $this->groupCache['comment'];
            foreach (['证书', '培训经历', '兴趣爱好'] as $title) {
                if ($part = $this->getPart($title)) $resultText .= "\r\n\r\n" . $title . "\r\n" . $part;
            }
            return trim($resultText);
        };

        $this->get['avatar'] = function () {
            try {
                //$this->listXPath("//table/tr[td/table/tr/td[p/b/span[contains(@style, 'font-size:16.0pt')] and contains(following-sibling::td, '手机：')]]/following-sibling::tr[1]//img[1]/@src");
                $result = $this->xPath->query("//table/tr[td/table/tr/td[p/b/span[contains(@style, 'font-size:16.0pt')]]]/following-sibling::tr[1]//img[1]/@src");
                if (!count($result) || empty($url = $result[0]->textContent) || preg_match('/\/personpic.*?\.png$/i', $url)) return '';

                return ['url' => $url, 'name' => basename($url)];
            } catch (\Exception $e) {
                Log::error(e_dump($e), ['avatar' => $url ?? ''], 'cmd');
                return '';
            }
        };
    }
}
